import { useAppDispatch, useAppSelector } from '../store';
import { checkedAllAction, deleteByIdAction, updateByIdAction } from '../store/action/todo';

export default function Main() {
  const { list, type } = useAppSelector((state) => state.todo);
  const dispatch = useAppDispatch();
  const computedList = list.filter((item) => {
    if (type === 'active') {
      return !item.isDone;
    }
    if (type === 'completed') {
      return item.isDone;
    }
    return item;
  });
  const allChecked = list.length > 0 && list.every((item) => item.isDone);
  const checkAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    dispatch(checkedAllAction(e.target.checked));
  };
  return (
    <section className="main">
      <input id="toggle-all" className="toggle-all" type="checkbox" checked={allChecked} onChange={checkAll} />
      <label htmlFor="toggle-all">全选</label>
      <ul className="todo-list">
        {computedList.map((item) => {
          return (
            <li key={item.id} className={item.isDone ? 'completed' : ''}>
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={item.isDone}
                  onChange={() => dispatch(updateByIdAction(item.id))}
                />
                <label>{item.task}</label>
                <button onClick={() => dispatch(deleteByIdAction(item.id))} className="destroy"></button>
              </div>
            </li>
          );
        })}
      </ul>
    </section>
  );
}
